import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import session from '@/utils/SessionStorageUtil'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  withCredentials: true,
  timeout: 5000
})
/**
 * 请求拦截
 */
service.interceptors.request.use(
  config => {
    const token = session.GET('big_data_token') || { token: 'null' }
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.headers.Authorization = token.token
    return config
  }, error => {
    return Promise.reject(error)
  })
/**
 * 响应拦截
 */
service.interceptors.response.use(
  response => {
    return response
  }, error => {
    return Promise.reject(error)
  })
/**
 * 处理 response成功结果【Token失效,成功,···】【注意，不同后端成功的CODE可能不一样哦】
 * @param response
 * @returns {boolean}
 */
const handleApiResponseStatus = response => {
  const code = response.data.code
  if (code === 0 || code === 200) {
    return true
  } else if (code === 200002) {
    handleUrlRedirect(response)
  } else {
    Message({
      showClose: true,
      message: response.data.message || '服务器异常',
      type: 'error'
    })
    console.log('----------------------------------------------------------------')
    console.log('接口：' + response.config.url)
    console.log('状态：' + response.data.code)
    console.log('报文：' + response.data.message)
    console.log('----------------------------------------------------------------')
    return true
  }
}
/**
 * 网络异常
 * @param error
 * @returns {boolean}
 */
const handleHttpResponseStatus = error => {
  console.log('----------------------------------------------------------------')
  console.log('接口：' + error.config.url)
  console.log('状态：' + error.response.data.code)
  console.log('报文：' + error.response.data.message)
  console.log('----------------------------------------------------------------')
}
/**
 * 页面重定向【Token过期,失效之类的需要重新跳转到登录页面】
 */
const handleUrlRedirect = (response) => {
  Message({
    showClose: true,
    message: response.data.message || '登录过期，请重新登录',
    type: 'error',
    onClose: () => {
      session.DEL('big_data_menuInfo')
      session.DEL('big_data_userInfo')
      session.DEL('big_data_token')
      router.push('/login')
    }
  })
}
/**
 * GET
 * @param params
 * @returns {Promise<unknown>}
 * @constructor
 */
export function GET (url, params = {}) {
  return new Promise((resolve, reject) => {
    service.get(url, params).then(response => {
      if (handleApiResponseStatus(response)) resolve(response.data)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}
/**
 * POST
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 * @constructor
 */
export function POST (url = '', data = {}) {
  return new Promise((resolve, reject) => {
    service.post(url, data).then(response => {
      if (handleApiResponseStatus(response)) resolve(response.data)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}
/**
 * DELETE
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 * @constructor
 */
export function DELETE (url, params = {}) {
  return new Promise((resolve, reject) => {
    service.delete(url, params).then(response => {
      if (handleApiResponseStatus(response)) resolve(response.data)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}
/**
 * DOWNLOAD
 * @param params
 * @returns {Promise<unknown>}
 * @constructor
 */
export function DOWNLOAD (params) {
  return new Promise((resolve, reject) => {
    service.post(params.url, params.data, { responseType: 'arraybuffer' }).then(response => {
      if (handleApiResponseStatus(response)) resolve(response.data)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}

export function EXPORT (url = '', data = {}, fileName) {
  return new Promise((resolve, reject) => {
    service.post(url, data, { responseType: 'blob' }).then(response => {
      const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.setAttribute('download', `${fileName}.xls`)
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      document.body.append(link)
      link.click()
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    }).catch(error => {
      if (handleHttpResponseStatus(error)) reject(error)
    })
  })
}
